<?php
/**
 * 我的收货地址逻辑处理
 * User：LLW
 * Date:2020-03-25
 */

namespace app\api\model;

use think\Model;
use think\Session;

class AddressModel extends Model
{
    protected $table = 'yc_address';

    /**
     * 收货地址逻辑
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList()
    {
        $uid = Session::get('uid');
        $list = $this->where('ad_uid',$uid)->select();
        AjaxReturn(1,'OK',$list);
    }

    /**
     * 添加编辑逻辑
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function postAddEdit()
    {
        $date = input('post.');
        $uid = Session::get('uid');
        $data['ad_default'] = empty($date['isDefault']) ? 0 : $date['isDefault'];
        $data['ad_name'] = $date['name'];
        $data['ad_phone'] = $date['tel'];
        $data['ad_area'] = $date['province'].' '.$date['city'].' '.$date['county'];
        $data['ad_addre'] = $date['addressDetail'];
        $data['ad_id'] = input('ad_id',null);
        if($data['ad_default'] == 1){
            $list = $this->where(['ad_default'=>1,'ad_uid'=>$uid])->select();
            if(!empty($list)){
                AjaxReturn(-1,'每个账号只可存在一个默认地址');
            }
        }
        $lists = $this->where(['ad_uid'=>$uid])->count();
        if($lists > tpConfig('Ushou')){
            AjaxReturn(-1,'收货地址最多存在'.tpConfig('Ushou').'个');
        }
        $data['ad_uid'] = $uid;
        if(!empty($data['ad_id'])){
            $res = $this->where('ad_id',$data['ad_id'])->update($data);
        }else{
            unset($data['ad_id']);
            $res = $this->insert($data);
        }
        if($res){
            AjaxReturn(1,'成功');
        }else{
            AjaxReturn(-1,'失败');
        }
    }

    /**
     * 获取详细信息逻辑
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFind()
    {
        $id = input('id',null);
        $find = $this->where('ad_id',$id)->find();
        if(empty($find)){
            AjaxReturn(-1,'地址信息获取错误');
        }
        $arr = array_filter(explode(' ',$find['ad_area']));
        $find['province'] = $arr[0];
        $find['city'] = $arr[1];
        if(isset($arr[2])){
            $find['county'] = $arr[2];
        }
        if(isset($arr[3])){
            $find['county'] = $arr[3];
        }
        if($find['ad_default'] == 1){
            $find['ad_default'] = true;
        }else{
            $find['ad_default'] = false;
        }
        AjaxReturn(1,'ok',$find);
    }
}